package com.gzz.orchid.common.webmvc.support.repeatsubmit;


import com.gzz.orchid.common.core.authorization.UserContextHolder;
import com.gzz.orchid.common.core.util.StringUtil;
import com.gzz.orchid.common.webmvc.support.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author higmd
 * 下单前获取令牌用于防重提交
 */
@Slf4j
@RestController("/repeat-submit")
public class ReSubmitTokenApi {
    /**
     * 提交订单令牌的缓存key
     */
    public static final String SUBMIT_ORDER_TOKEN_KEY = "order:submit:%s:%s";
    /**
     * 获取随机长度的串
     *
     * @param length
     * @return
     */
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 下单前获取令牌用于防重提交
     *
     * @return
     */
    @GetMapping("token")
    public HttpResult getOrderToken() {
        //获取登录账户
        long accountNo = UserContextHolder.currentUser().getUserId();
        //随机获取32位的数字+字母作为token
        String token = StringUtil.randomString(32);
        //key的组成
        String key = String.format(ReSubmit.DEFAULT_TOKEN_KEY, accountNo, token);
        //令牌有效时间是30分钟
        redisTemplate.opsForValue()
                .set(key, String.valueOf(Thread.currentThread().getId()), 30, TimeUnit.MINUTES);

        return HttpResult.success().data(token);
    }
}
